package com.gyms.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.classic.okhttp.AppChangeUtils;
import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVUserBaseInfoBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.DataCenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import utils.ActivityStack;
import utils.DataUtil;
import utils.RegexUtils;
import utils.StringUtils;
import weight.PhoneEditText;
import weight.TimeButton;
import weight.UiEvent;

/**
 * 验证码登录 yjl
 */
public class CodeLoginActivity extends MyAutoLayoutActivity {
    @BindView(R.id.et_phone)
    PhoneEditText etPhone;//手机号输入框
    @BindView(R.id.btn_getcode)
    TimeButton btnGetcode;
    @BindView(R.id.et_code)
    PhoneEditText etCode;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.login_by_psw)
    TextView mLoginByPsw;

    private String phone;
    private String code;
    private boolean isToMain;//判断是否要跳转到主页

    private String mFunction;//JS登录的回调函数
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_code_login;
    }

    @Override
    protected void initView() {
        initData();
        //注册EventBus
        EventBus.getDefault().register(this);
        ActivityStack.getInstance().addActivity(this);
        setTitle("验证码登录");
        mTitleManager.setLeftCloseImg(R.drawable.city_close_selector);
        mTitleManager.getmLeftView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        setBack();
        createLoadingView("加载中", true);
        isToMain=getIntent().getBooleanExtra("isToMain",false);
        tvTips.setText(AppChangeUtils.LOGIN_TEXT);
        tvTips.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        tvTips.getPaint().setAntiAlias(true);//抗锯齿
        tvTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("title", ((TextView) v).getText());
                intent.putExtra("url", Cons.cooperationUrl);
                startActivity(intent, false);
            }
        });
    }

    private void initData() {
        Bundle mBundle=getIntent().getExtras();
        if(null!=mBundle){
            mFunction=mBundle.getString(Constants.KEY_LOGIN_FUN);
        }
    }

    @Override
    protected void setListener() {
    }

    @Override
    protected void processLogic() {

    }

    @OnClick({R.id.btn_getcode, R.id.btn_login,R.id.login_by_psw})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login://登录
                if (verification()) {
                    if (loadingView != null) {
                        loadingView.show();
                    }
                    IUserService.loginVerify(this, phone, code, null,false, new ObjectCallback<String>() {
                        @Override
                        public void onSuccess(String response, String message) {
                            dialogDis();
                            DataCenter.getInstance().setToken(response);
                            //登录成功存储到本地
                            DataUtil.setSharePre(mContext,"token",response);
                            notifeMyinfo();
                            EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_DO_REGIST_PUSH,null));
                            doJsFunction();
                        }

                        @Override
                        public void onErrorT(int code, String response, String errorMessage) {
                            ToastUtil.showToast(mContext, errorMessage);
                            dialogDis();
                            etCode.requestFocus();

                        }

                        @Override
                        public void onHttpErrorCall(int statusCode) {
                            dialogDis();
                            etCode.requestFocus();
                        }
                    });
                }
                break;
            case R.id.btn_getcode:
                //请求签证码
                phone = etPhone.getText().toString().trim();
                phone= StringUtils.removeAllSpace(phone);
                if (!RegexUtils.isMobileSimple(phone)) {
                    ToastUtil.showToast(mContext, "请输入正确的手机号");
                    return;
                }
                reQuestVerify();
                break;
            case R.id.login_by_psw:
                phone = etPhone.getText().toString().trim();
                phone= StringUtils.removeAllSpace(phone);
                Intent intent=new Intent(mContext,LoginActivity.class);
                if(!StringUtils.isNull(mFunction)){
                    intent.putExtra(Constants.KEY_LOGIN_FUN,mFunction);
                }
                intent.putExtra("isToMain",isToMain);
                intent.putExtra(Constants.STR_PHONE,phone);
                startActivity(intent,false);
                break;
        }
    }

    /**
     * js 回调 登录状态
     */

    private void doJsFunction() {
        if(StringUtils.isNull(mFunction)){
            return;
        }
        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_LOGIN_SUCCESS,mFunction));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (btnGetcode != null) {
            btnGetcode.clearTimer();
        }
        doJSCancelLogin();
        ActivityStack.getInstance().finishActivity(this);
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
    }

    /**
     * 取消登录的回调
     */

    private void doJSCancelLogin() {
        if(DataCenter.getInstance().checkIsLogin()||StringUtils.isNull(mFunction)){//没有登录并且function不为null
            return;
        }
        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_LOGIN_CANCEL,mFunction));
    }

    /**
     * 表单验证
     */
    private boolean verification() {
        phone = etPhone.getText().toString().trim();
        phone= StringUtils.removeAllSpace(phone);
        code = etCode.getText().toString().trim();
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtil.showToast(mContext, "请输入正确的手机号");
            return false;
        } else if ("".equals(code)) {
            ToastUtil.showToast(mContext, "请输入验证码");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 请求验证码接口
     */
    private void reQuestVerify() {
        loadingView.show();
        IUserService.getVerify(this, phone, Enum.EnumVerifyType.Login, false, new ObjectCallback<Object>() {
            @Override
            public void onSuccess(Object response, String message) {
                dialogDis();
                ToastUtil.showToast(mContext, "验证码发送成功");
                //获取验证码成功后 验证码获取焦点 并弹出软键盘
//                KeyboardUtils.showSoftInputFromWindow(CodeLoginActivity.this,etCode);
                etCode.requestFocus();
                btnGetcode.setStartOrNot(true);
            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {
                dialogDis();
                ToastUtil.showToast(mContext, errorMessage);

            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }


    /**
     * 通知刷新我的信息
     */
    private void notifeMyinfo() {
        EventBus.getDefault().post(new UiEvent(EventConstant.S_MYINFO, null));
    }

    /**
     * EventBus 接收事件
     * 刷新我的信息
     *
     * @param uiEvent
     */
    @Subscribe
    public void toReflashMyInfo(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.S_CODE)) {
            if (!StringUtils.isNull(uiEvent.getObject())) {
                if (!((HVUserBaseInfoBean)uiEvent.getObject()).getIsSetPwd()) {
                    ToastUtil.showToast(mContext,"请设置密码");
                    Bundle mBundle=new Bundle();
                    mBundle.putBoolean(Constants.KEY_MUST_MODIFY,true);
                    startActivity(FirstEditPassActivity.class, mBundle,true);
                    overridePendingTransition(R.anim.activity_open, R.anim.activity_stay);//向上弹出
                    /*ActivityStack.getInstance().finishActivity(LoginActivity.class);*/
                }else {
                    toIntent();
                }
            }else {
                toIntent();
            }
        }else if(uiEvent.getKey().equals(EventConstant.FLAG_LOGIN_PSW)){//密码登录成功后关掉 当前页面
            finish();
        }else if(EventConstant.FLAG_CHANGE_PHONE_NUM.equals( uiEvent.getKey())){
            String mTempPhone= (String) uiEvent.getObject();
            etPhone.setText(mTempPhone);
            if(!StringUtils.isNull(mTempPhone)){
                etPhone.setSelection(etPhone.getText().toString().trim().length());
            }else {
                etPhone.requestFocus();
            }
        }
    }

    private void toIntent() {
        if (isToMain) {
//            ActivityStack.getInstance().finishActivity(LoginActivity.class);
            startActivity(MainActivity.class, true);
        } else {
//            ActivityStack.getInstance().finishActivity(LoginActivity.class);
            onBackPressed();

        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        hideKeyBoard(ev);//隐藏软键盘
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_close_in, R.anim.activity_close_out);
//        ActivityStack.getInstance().finishActivity(CodeLoginActivity.class);
    }

}
